﻿using Markdig;
using Markdig.Parsers;
using Markdig.Renderers;
using Markdig.Renderers.Html;
using Markdig.Syntax;

namespace KnownCMS.Extensions;

/// <summary>
/// 
/// </summary>
public class MermaidExtension : IMarkdownExtension
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="pipeline"></param>
    public void Setup(MarkdownPipelineBuilder pipeline)
    {
        pipeline.BlockParsers.AddIfNotAlready<MermaidParser>();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="pipeline"></param>
    /// <param name="renderer"></param>
    public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
    {
        if (renderer is HtmlRenderer htmlRenderer)
        {
            htmlRenderer.ObjectRenderers.AddIfNotAlready<MermaidRenderer>();
        }
    }
}

/// <summary>
/// 
/// </summary>
public class MermaidParser : FencedCodeBlockParser
{
    /// <summary>
    /// 
    /// </summary>
    public MermaidParser() : base()
    {
        InfoPrefix = "mermaid-";
        OpeningCharacters = ['`']; // 匹配 ```mermaid
    }
}

/// <summary>
/// 
/// </summary>
public class MermaidRenderer : HtmlObjectRenderer<FencedCodeBlock>
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="renderer"></param>
    /// <param name="block"></param>
    protected override void Write(HtmlRenderer renderer, FencedCodeBlock block)
    {
        // 检查语言标签是否为 "mermaid"
        if (block.Info == "mermaid")
        {
            // 包裹在带 mermaid 类的 div 中
            renderer.WriteLine("<div class=\"mermaid\">");
            renderer.WriteEscape(block.Lines.ToString());
            renderer.WriteLine("</div>");
        }
        else
        {
            // 默认代码块渲染
            renderer.Write("<pre><code>");
            renderer.WriteEscape(block.Lines.ToString());
            renderer.WriteLine("</code></pre>");
        }
    }
}